package br.com.jk.financeiro.movimento;

import br.com.jk.cliente.Cliente;
import br.com.jk.cliente.ClienteJDialog;
import br.com.jk.financeiro.contaBanco.*;
import br.com.jk.empresa.Empresa;
import br.com.jk.empresa.EmpresaJDialog;
import br.com.jk.financeiro.banco.*;
import br.com.jk.financeiro.movimentotipo.MovimentoTipo;
import br.com.jk.financeiro.movimentotipo.MovimentoTipo.Tipo;
import br.com.jk.financeiro.movimentotipo.MovimentoTipoJDialog;
import br.com.jk.fornecedor.Fornecedor;
import br.com.jk.fornecedor.FornecedorJDialog;
import br.com.jk.util.ControllerException;
import br.com.jk.util.StatusType;
import br.com.jk.util.StatusType.Status;
import br.com.jk.util.Util;
import java.awt.event.KeyEvent;
import java.math.BigDecimal;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author camilo
 */
public class MovimentoJDialog extends javax.swing.JDialog {

  private static MovimentoJDialog dialog;
  // Model da tabela
  MovimentoTableModel movimentoTm = new MovimentoTableModel();
  MovimentoController control = new MovimentoController();
//  atributos utilizados nas pesquisas externas
  private JTextField idPesquisa;
  private JTextField razaoPesquisa;
  private boolean modoConsultaExt;
  private Integer id;
  private ContaBanco contaBanco;
  private MovimentoTipo movimentoTipo;

  public static MovimentoJDialog getInstance(java.awt.Frame parent, boolean modal) {
    if (dialog == null) {
      dialog = new MovimentoJDialog(parent, modal);
    }
    return dialog;
  }

  public static MovimentoJDialog getInstance(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    if (dialog == null) {
      dialog = new MovimentoJDialog(parent, modal, id, razao);
    }
    return dialog;
  }

  /**
   * Creates new form FornecedorJDialog
   */
  private MovimentoJDialog(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    init();
  }

  private MovimentoJDialog(java.awt.Frame parent, boolean modal, JTextField id, JTextField razao) {
    super(parent, modal);
    this.idPesquisa = id;
    this.razaoPesquisa = razao;
    this.modoConsultaExt = true;

    initComponents();
    init();
  }

  private void init() {
    criaModel();
    setLocationRelativeTo(null);
    jlFiltro.setVisible(false);
    jtfIdConta.requestFocus();
  }

  private void criaModel() {
    jtMovimento.setModel(movimentoTm);

    movimentoTm.sorter(jtMovimento, movimentoTm);

    /*jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_ID).setPreferredWidth(60);
     jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_DESCRICAO).setPreferredWidth(245);
     jtProduto.getColumnModel().getColumn(ProdutoTableModel.COLUNA_COD_NOME_UF).setPreferredWidth(40);*/
  }

  /**
   * This method is called from within the constructor to initialize the form. WARNING: Do
   * NOT modify this code. The content of this method is always regenerated by the Form
   * Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    JtbMaster = new javax.swing.JToolBar();
    JbNovo = new javax.swing.JButton();
    JbSalvar = new javax.swing.JButton();
    JbEditar = new javax.swing.JButton();
    JbCancelar = new javax.swing.JButton();
    JbExcluir = new javax.swing.JButton();
    jbBuscar = new javax.swing.JButton();
    JbRelatorio = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    JbRefresh = new javax.swing.JButton();
    jlFiltro = new javax.swing.JLabel();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jpLancamento = new javax.swing.JPanel();
    jpConta = new javax.swing.JPanel();
    jLabel10 = new javax.swing.JLabel();
    jtfIdConta = new javax.swing.JTextField();
    jtfDescConta = new javax.swing.JTextField();
    jbReiniciar = new javax.swing.JButton();
    jspMovimento = new javax.swing.JSplitPane();
    jpDados = new javax.swing.JPanel();
    jLabel1 = new javax.swing.JLabel();
    jtfDataPrevisao = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    jtfObservacao = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    jtfDataLancamento = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jtfIdCliente = new javax.swing.JTextField();
    jtfNameCliente = new javax.swing.JTextField();
    jtfIdFornecedor = new javax.swing.JTextField();
    jtfNameFornecedor = new javax.swing.JTextField();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    jLabel11 = new javax.swing.JLabel();
    jcbStatus = new javax.swing.JComboBox();
    jLabel12 = new javax.swing.JLabel();
    jLabel13 = new javax.swing.JLabel();
    jtfIdTipo = new javax.swing.JTextField();
    jtfNameTipo = new javax.swing.JTextField();
    jtfDataRealizado = new javax.swing.JTextField();
    jtfValor = new javax.swing.JTextField();
    jtfNumDocumento = new javax.swing.JTextField();
    jtfNumCheque = new javax.swing.JTextField();
    jSeparator3 = new javax.swing.JSeparator();
    jpJTable = new javax.swing.JPanel();
    jScrollPane1 = new javax.swing.JScrollPane();
    jtMovimento = new javax.swing.JTable();
    jpGerenciar = new javax.swing.JPanel();

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    setTitle("Movimentação Bancária");
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosed(java.awt.event.WindowEvent evt) {
        formWindowClosed(evt);
      }
    });

    JtbMaster.setRollover(true);

    JbNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-new.png"))); // NOI18N
    JbNovo.setToolTipText("Novo Registro");
    JbNovo.setEnabled(false);
    JbNovo.setFocusable(false);
    JbNovo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbNovo.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbNovo.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbNovoActionPerformed(evt);
      }
    });
    JtbMaster.add(JbNovo);

    JbSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-save-hd.png"))); // NOI18N
    JbSalvar.setToolTipText("Salvar Registro");
    JbSalvar.setEnabled(false);
    JbSalvar.setFocusable(false);
    JbSalvar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbSalvar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbSalvar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbSalvarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbSalvar);

    JbEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/document-edit.png"))); // NOI18N
    JbEditar.setToolTipText("Alterar registro");
    JbEditar.setEnabled(false);
    JbEditar.setFocusable(false);
    JbEditar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbEditar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbEditar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbEditarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbEditar);

    JbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/dialog-cancel.png"))); // NOI18N
    JbCancelar.setToolTipText("Cancelar");
    JbCancelar.setEnabled(false);
    JbCancelar.setFocusable(false);
    JbCancelar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbCancelar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbCancelar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbCancelarActionPerformed(evt);
      }
    });
    JtbMaster.add(JbCancelar);

    JbExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/archive-remove.png"))); // NOI18N
    JbExcluir.setToolTipText("Excluir");
    JbExcluir.setEnabled(false);
    JbExcluir.setFocusable(false);
    JbExcluir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbExcluir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbExcluir.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbExcluirActionPerformed(evt);
      }
    });
    JtbMaster.add(JbExcluir);

    jbBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-find.png"))); // NOI18N
    jbBuscar.setToolTipText("Buscar");
    jbBuscar.setEnabled(false);
    jbBuscar.setFocusable(false);
    jbBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jbBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    jbBuscar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbBuscarActionPerformed(evt);
      }
    });
    JtbMaster.add(jbBuscar);

    JbRelatorio.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/report.png"))); // NOI18N
    JbRelatorio.setToolTipText("Relatórios");
    JbRelatorio.setEnabled(false);
    JbRelatorio.setFocusable(false);
    JbRelatorio.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRelatorio.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRelatorio.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRelatorioActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRelatorio);
    JtbMaster.add(jSeparator1);

    JbRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/view-refresh.png"))); // NOI18N
    JbRefresh.setToolTipText("Atualizar registros da lista");
    JbRefresh.setEnabled(false);
    JbRefresh.setFocusable(false);
    JbRefresh.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    JbRefresh.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    JbRefresh.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        JbRefreshActionPerformed(evt);
      }
    });
    JtbMaster.add(JbRefresh);

    jlFiltro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/task-attempt.png"))); // NOI18N
    JtbMaster.add(jlFiltro);
    JtbMaster.add(jSeparator2);

    jTabbedPane1.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N

    jLabel10.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jLabel10.setText("Conta Bancária");

    jtfIdConta.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdConta.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdContaKeyPressed(evt);
      }
    });

    jtfDescConta.setEditable(false);
    jtfDescConta.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N

    jbReiniciar.setFont(new java.awt.Font("Liberation Sans", 1, 12)); // NOI18N
    jbReiniciar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/jk/imagens/edit-undo.png"))); // NOI18N
    jbReiniciar.setMnemonic('r');
    jbReiniciar.setText("Reiniciar");
    jbReiniciar.setToolTipText("Selecionar outra conta bancária");
    jbReiniciar.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jbReiniciarActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout jpContaLayout = new javax.swing.GroupLayout(jpConta);
    jpConta.setLayout(jpContaLayout);
    jpContaLayout.setHorizontalGroup(
      jpContaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpContaLayout.createSequentialGroup()
        .addGap(3, 3, 3)
        .addGroup(jpContaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(jpContaLayout.createSequentialGroup()
            .addComponent(jLabel10)
            .addContainerGap(554, Short.MAX_VALUE))
          .addGroup(jpContaLayout.createSequentialGroup()
            .addComponent(jtfIdConta, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jtfDescConta)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jbReiniciar))))
    );
    jpContaLayout.setVerticalGroup(
      jpContaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpContaLayout.createSequentialGroup()
        .addComponent(jLabel10)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addGroup(jpContaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(jtfIdConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jtfDescConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jbReiniciar)))
    );

    jspMovimento.setDividerLocation(140);
    jspMovimento.setDividerSize(10);
    jspMovimento.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
    jspMovimento.setAutoscrolls(true);
    jspMovimento.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jspMovimento.setOneTouchExpandable(true);

    jpDados.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Dados"));
    java.awt.GridBagLayout jpDadosLayout = new java.awt.GridBagLayout();
    jpDadosLayout.columnWidths = new int[] {60, 130, 130, 10, 100, 100, 100};
    jpDados.setLayout(jpDadosLayout);

    jLabel1.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel1.setText("Data Lançamento");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel1, gridBagConstraints);

    jtfDataPrevisao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataPrevisao.setEnabled(false);
    jtfDataPrevisao.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfDataPrevisaoFocusGained(evt);
      }
    });
    jtfDataPrevisao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDataPrevisaoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataPrevisao, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel3.setText("Observação");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel3, gridBagConstraints);

    jtfObservacao.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfObservacao.setEnabled(false);
    jtfObservacao.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfObservacaoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtfObservacaoKeyReleased(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridwidth = 7;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfObservacao, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel4.setText("Data Previsão");
    jLabel4.setToolTipText("Data Cadastro");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel4, gridBagConstraints);

    jtfDataLancamento.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataLancamento.setEnabled(false);
    jtfDataLancamento.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDataLancamentoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfDataLancamento, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel5.setText("Cliente");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel5, gridBagConstraints);

    jLabel6.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel6.setText("Fornecedor");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel6, gridBagConstraints);

    jtfIdCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdCliente.setEnabled(false);
    jtfIdCliente.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfIdClienteFocusGained(evt);
      }
    });
    jtfIdCliente.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdClienteKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    jpDados.add(jtfIdCliente, gridBagConstraints);

    jtfNameCliente.setEditable(false);
    jtfNameCliente.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameCliente.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfNameCliente, gridBagConstraints);

    jtfIdFornecedor.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdFornecedor.setEnabled(false);
    jtfIdFornecedor.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfIdFornecedorFocusGained(evt);
      }
    });
    jtfIdFornecedor.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdFornecedorKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfIdFornecedor, gridBagConstraints);

    jtfNameFornecedor.setEditable(false);
    jtfNameFornecedor.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameFornecedor.setEnabled(false);
    jtfNameFornecedor.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        jtfNameFornecedorActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    jpDados.add(jtfNameFornecedor, gridBagConstraints);

    jLabel7.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel7.setText("Data Realizado");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel7, gridBagConstraints);

    jLabel8.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel8.setText("Valor");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel8, gridBagConstraints);

    jLabel9.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel9.setText("Nº Doc.");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel9, gridBagConstraints);

    jLabel11.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel11.setText("Status");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel11, gridBagConstraints);

    jcbStatus.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jcbStatus.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 5;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jcbStatus, gridBagConstraints);

    jLabel12.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel12.setText("Tipo");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel12, gridBagConstraints);

    jLabel13.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jLabel13.setText("Nº Cheque");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LAST_LINE_START;
    jpDados.add(jLabel13, gridBagConstraints);

    jtfIdTipo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfIdTipo.setEnabled(false);
    jtfIdTipo.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusLost(java.awt.event.FocusEvent evt) {
        jtfIdTipoFocusLost(evt);
      }
    });
    jtfIdTipo.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfIdTipoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfIdTipo, gridBagConstraints);

    jtfNameTipo.setEditable(false);
    jtfNameTipo.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNameTipo.setEnabled(false);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfNameTipo, gridBagConstraints);

    jtfDataRealizado.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfDataRealizado.setEnabled(false);
    jtfDataRealizado.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfDataRealizadoFocusGained(evt);
      }
    });
    jtfDataRealizado.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfDataRealizadoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfDataRealizado, gridBagConstraints);

    jtfValor.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfValor.setEnabled(false);
    jtfValor.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfValorKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 6;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfValor, gridBagConstraints);

    jtfNumDocumento.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNumDocumento.setEnabled(false);
    jtfNumDocumento.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfNumDocumentoFocusGained(evt);
      }
    });
    jtfNumDocumento.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNumDocumentoKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfNumDocumento, gridBagConstraints);

    jtfNumCheque.setFont(new java.awt.Font("Liberation Sans", 0, 12)); // NOI18N
    jtfNumCheque.setEnabled(false);
    jtfNumCheque.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        jtfNumChequeFocusGained(evt);
      }
    });
    jtfNumCheque.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtfNumChequeKeyPressed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    jpDados.add(jtfNumCheque, gridBagConstraints);

    jSeparator3.setOrientation(javax.swing.SwingConstants.VERTICAL);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridheight = 6;
    gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL;
    jpDados.add(jSeparator3, gridBagConstraints);

    jspMovimento.setBottomComponent(jpDados);

    /*jtMovimento.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtMovimento.getSelectedRow();
        fControl.selecionado();
      }
    });

    jtMovimento.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener(){
      public void valueChanged(ListSelectionEvent evt){
        if (evt.getValueIsAdjusting()){
          return;
        }
        int selected = jtMovimento.getSelectedColumn();
        fControl.selecionado();
      }
    });*/
    jtMovimento.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
    jtMovimento.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        jtMovimentoMouseClicked(evt);
      }
    });
    jtMovimento.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyPressed(java.awt.event.KeyEvent evt) {
        jtMovimentoKeyPressed(evt);
      }
      public void keyReleased(java.awt.event.KeyEvent evt) {
        jtMovimentoKeyReleased(evt);
      }
    });
    jScrollPane1.setViewportView(jtMovimento);

    javax.swing.GroupLayout jpJTableLayout = new javax.swing.GroupLayout(jpJTable);
    jpJTable.setLayout(jpJTableLayout);
    jpJTableLayout.setHorizontalGroup(
      jpJTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 644, Short.MAX_VALUE)
    );
    jpJTableLayout.setVerticalGroup(
      jpJTableLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 140, Short.MAX_VALUE)
    );

    jspMovimento.setLeftComponent(jpJTable);

    javax.swing.GroupLayout jpLancamentoLayout = new javax.swing.GroupLayout(jpLancamento);
    jpLancamento.setLayout(jpLancamentoLayout);
    jpLancamentoLayout.setHorizontalGroup(
      jpLancamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpLancamentoLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(jpLancamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(jpConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(jspMovimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jpLancamentoLayout.setVerticalGroup(
      jpLancamentoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(jpLancamentoLayout.createSequentialGroup()
        .addContainerGap()
        .addComponent(jpConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jspMovimento, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)
        .addContainerGap())
    );

    jTabbedPane1.addTab("Lançamento", jpLancamento);

    javax.swing.GroupLayout jpGerenciarLayout = new javax.swing.GroupLayout(jpGerenciar);
    jpGerenciar.setLayout(jpGerenciarLayout);
    jpGerenciarLayout.setHorizontalGroup(
      jpGerenciarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 668, Short.MAX_VALUE)
    );
    jpGerenciarLayout.setVerticalGroup(
      jpGerenciarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGap(0, 419, Short.MAX_VALUE)
    );

    jTabbedPane1.addTab("Gerenciamento", jpGerenciar);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addComponent(JtbMaster, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
      .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addComponent(JtbMaster, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addComponent(jTabbedPane1)
        .addContainerGap())
    );

    pack();
  }// </editor-fold>//GEN-END:initComponents

  private void JbNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbNovoActionPerformed
    novo();
  }//GEN-LAST:event_JbNovoActionPerformed

  private void JbSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbSalvarActionPerformed
    salvar();
  }//GEN-LAST:event_JbSalvarActionPerformed

  private void JbEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbEditarActionPerformed
    editar();
  }//GEN-LAST:event_JbEditarActionPerformed

  private void JbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbCancelarActionPerformed
    cancelar();
  }//GEN-LAST:event_JbCancelarActionPerformed

  private void JbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbExcluirActionPerformed
    excluir();
  }//GEN-LAST:event_JbExcluirActionPerformed

  private void jbBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbBuscarActionPerformed
    pesquisar();
  }//GEN-LAST:event_jbBuscarActionPerformed

  private void JbRelatorioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRelatorioActionPerformed
    try {
//      Master.setJpbStatusIndeterminate(true);
//      Master.setTextJlStatus("Gerando relatório...");
      ThreadReport thReport = new ThreadReport();
      thReport.start();

    } catch (Exception e) {
      Util.msgErro(e, "Erro ao gerar o relatório");
    }
  }//GEN-LAST:event_JbRelatorioActionPerformed

  private void JbRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JbRefreshActionPerformed
    listar();
    jlFiltro.setVisible(false);
    jbBuscar.setEnabled(false);
  }//GEN-LAST:event_JbRefreshActionPerformed

  private void jtMovimentoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtMovimentoMouseClicked
    if (movimentoTm.getRowCount() > 0 && (id != null && jtfObservacao != null)) {
      selecionado();
    }
  }//GEN-LAST:event_jtMovimentoMouseClicked

  private void jtfDataPrevisaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDataPrevisaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfDataRealizado.requestFocus();
    }
  }//GEN-LAST:event_jtfDataPrevisaoKeyPressed

  private void jtfObservacaoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfObservacaoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      salvar();
    }
  }//GEN-LAST:event_jtfObservacaoKeyPressed

  private void jtfDataLancamentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDataLancamentoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfDataPrevisao.requestFocus();
    }
  }//GEN-LAST:event_jtfDataLancamentoKeyPressed

  private void jtMovimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtMovimentoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_SPACE) {
      if (jbBuscar.isEnabled()) {
        pesquisar();
      }
    } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (modoConsultaExt) {
        selecionaRegistro();
      }
    }
  }//GEN-LAST:event_jtMovimentoKeyPressed

  private void jtfObservacaoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfObservacaoKeyReleased
    Util.setFirstLetterUpperCase(jtfObservacao, jtfObservacao.getSelectionStart());
  }//GEN-LAST:event_jtfObservacaoKeyReleased

  private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    dialog = null;
  }//GEN-LAST:event_formWindowClosed

  private void jtfNameFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfNameFornecedorActionPerformed
    // TODO add your handling code here:
  }//GEN-LAST:event_jtfNameFornecedorActionPerformed

  private void jtfIdClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdClienteKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdCliente.getText().isEmpty()) {
        selecionaCliente();
      }
      if (jtfNameCliente.getText().isEmpty()) {
        Cliente cli = control.carregaCliente(Integer.parseInt(jtfIdCliente.getText()));
        jtfNameCliente.setText(cli.getFantasia());
      }
      jtfDataLancamento.requestFocus();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaCliente();
    }
  }//GEN-LAST:event_jtfIdClienteKeyPressed

  private void jtfIdFornecedorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdFornecedorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdFornecedor.getText().isEmpty()) {
        selecionaFornecedor();
      }
      if (jtfNameFornecedor.getText().isEmpty()) {
        Fornecedor f = control.carregaFornecedor(Integer.parseInt(jtfIdFornecedor.getText()));
        jtfNameFornecedor.setText(f.getRazao());
      }
      jtfIdCliente.requestFocus();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaFornecedor();
    }
  }//GEN-LAST:event_jtfIdFornecedorKeyPressed

  private void jtMovimentoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtMovimentoKeyReleased
    if (evt.getKeyCode() == KeyEvent.VK_UP
            || evt.getKeyCode() == KeyEvent.VK_DOWN
            || evt.getKeyCode() == KeyEvent.VK_LEFT
            || evt.getKeyCode() == KeyEvent.VK_RIGHT) {
      selecionado();
    }
  }//GEN-LAST:event_jtMovimentoKeyReleased

  private void jtfIdContaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdContaKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdConta.getText().isEmpty()) {
        selecionaConta();
      }
      if (jtfDescConta.getText().isEmpty()) {
        contaBanco = control.carregaContaBanco(Integer.parseInt(jtfIdConta.getText()));
        jtfDescConta.setText(getDescConta(contaBanco));
      }
      setFirstCellSelect(jtMovimento, movimentoTm);
      JbNovo.setEnabled(true);
      JbRefresh.setEnabled(true);
      jtfIdConta.setEnabled(false);
      listar();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaConta();
    }
  }//GEN-LAST:event_jtfIdContaKeyPressed

  private void jtfIdTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfIdTipoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      if (jtfIdTipo.getText().isEmpty()) {
        selecionaTipo();
      }
      if (jtfNameTipo.getText().isEmpty()) {
        movimentoTipo = control.carregaTipo(Integer.parseInt(jtfIdTipo.getText()));
        jtfNameTipo.setText(movimentoTipo.getDescricao());
      }
      jtfIdFornecedor.requestFocus();
    } else if (evt.getKeyCode() == KeyEvent.VK_F12) {
      selecionaTipo();
    }
  }//GEN-LAST:event_jtfIdTipoKeyPressed

  private void jtfIdTipoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdTipoFocusLost
    validaTipo();
  }//GEN-LAST:event_jtfIdTipoFocusLost

  private void jtfIdFornecedorFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdFornecedorFocusGained
    if (!jtfIdFornecedor.isEnabled()) {
      jtfIdCliente.requestFocus();
    }
  }//GEN-LAST:event_jtfIdFornecedorFocusGained

  private void jtfIdClienteFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfIdClienteFocusGained
    if (!jtfIdCliente.isEnabled()) {
      jtfDataLancamento.requestFocus();
    }
  }//GEN-LAST:event_jtfIdClienteFocusGained

  private void jtfDataPrevisaoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfDataPrevisaoFocusGained
    if (!jtfDataPrevisao.isEnabled()) {
      jtfDataRealizado.requestFocus();
    }
  }//GEN-LAST:event_jtfDataPrevisaoFocusGained

  private void jtfDataRealizadoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfDataRealizadoFocusGained
    if (!jtfDataRealizado.isEnabled()) {
      jtfNumDocumento.requestFocus();
    }
  }//GEN-LAST:event_jtfDataRealizadoFocusGained

  private void jtfNumDocumentoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNumDocumentoFocusGained
    if (!jtfNumDocumento.isEnabled()) {
      jtfNumCheque.requestFocus();
    }
  }//GEN-LAST:event_jtfNumDocumentoFocusGained

  private void jtfNumChequeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtfNumChequeFocusGained
    if (!jtfNumCheque.isEnabled()) {
      jtfValor.requestFocus();
    }
  }//GEN-LAST:event_jtfNumChequeFocusGained

  private void jtfDataRealizadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfDataRealizadoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNumDocumento.requestFocus();
    }
  }//GEN-LAST:event_jtfDataRealizadoKeyPressed

  private void jtfNumDocumentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNumDocumentoKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfNumCheque.requestFocus();
    }
  }//GEN-LAST:event_jtfNumDocumentoKeyPressed

  private void jtfNumChequeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfNumChequeKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfValor.requestFocus();
    }
  }//GEN-LAST:event_jtfNumChequeKeyPressed

  private void jtfValorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfValorKeyPressed
    if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
      jtfObservacao.requestFocus();
    }
  }//GEN-LAST:event_jtfValorKeyPressed

  private void jbReiniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbReiniciarActionPerformed
    reiniciar();
  }//GEN-LAST:event_jbReiniciarActionPerformed

  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
      for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
        if ("Nimbus".equals(info.getName())) {
          javax.swing.UIManager.setLookAndFeel(info.getClassName());
          break;
        }
      }
    } catch (ClassNotFoundException ex) {
      java.util.logging.Logger.getLogger(MovimentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
      java.util.logging.Logger.getLogger(MovimentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
      java.util.logging.Logger.getLogger(MovimentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
      java.util.logging.Logger.getLogger(MovimentoJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the dialog */
    java.awt.EventQueue.invokeLater(new Runnable() {
      @Override
      public void run() {
        MovimentoJDialog dialog = new MovimentoJDialog(new javax.swing.JFrame(), true);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
          @Override
          public void windowClosing(java.awt.event.WindowEvent e) {
            System.exit(0);
          }
        });
        dialog.setVisible(true);
      }
    });
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton JbCancelar;
  private javax.swing.JButton JbEditar;
  private javax.swing.JButton JbExcluir;
  private javax.swing.JButton JbNovo;
  private javax.swing.JButton JbRefresh;
  private javax.swing.JButton JbRelatorio;
  private javax.swing.JButton JbSalvar;
  private javax.swing.JToolBar JtbMaster;
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel10;
  private javax.swing.JLabel jLabel11;
  private javax.swing.JLabel jLabel12;
  private javax.swing.JLabel jLabel13;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JLabel jLabel4;
  private javax.swing.JLabel jLabel5;
  private javax.swing.JLabel jLabel6;
  private javax.swing.JLabel jLabel7;
  private javax.swing.JLabel jLabel8;
  private javax.swing.JLabel jLabel9;
  private javax.swing.JScrollPane jScrollPane1;
  private javax.swing.JToolBar.Separator jSeparator1;
  private javax.swing.JToolBar.Separator jSeparator2;
  private javax.swing.JSeparator jSeparator3;
  private javax.swing.JTabbedPane jTabbedPane1;
  private javax.swing.JButton jbBuscar;
  private javax.swing.JButton jbReiniciar;
  private javax.swing.JComboBox jcbStatus;
  private javax.swing.JLabel jlFiltro;
  private javax.swing.JPanel jpConta;
  private javax.swing.JPanel jpDados;
  private javax.swing.JPanel jpGerenciar;
  private javax.swing.JPanel jpJTable;
  private javax.swing.JPanel jpLancamento;
  private javax.swing.JSplitPane jspMovimento;
  private javax.swing.JTable jtMovimento;
  private javax.swing.JTextField jtfDataLancamento;
  private javax.swing.JTextField jtfDataPrevisao;
  private javax.swing.JTextField jtfDataRealizado;
  private javax.swing.JTextField jtfDescConta;
  private javax.swing.JTextField jtfIdCliente;
  private javax.swing.JTextField jtfIdConta;
  private javax.swing.JTextField jtfIdFornecedor;
  private javax.swing.JTextField jtfIdTipo;
  private javax.swing.JTextField jtfNameCliente;
  private javax.swing.JTextField jtfNameFornecedor;
  private javax.swing.JTextField jtfNameTipo;
  private javax.swing.JTextField jtfNumCheque;
  private javax.swing.JTextField jtfNumDocumento;
  private javax.swing.JTextField jtfObservacao;
  private javax.swing.JTextField jtfValor;
  // End of variables declaration//GEN-END:variables

  public void novo() {
    limpar();
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);

    jtfIdTipo.requestFocus();
  }

  private void getLarguraJtBanco() {
    int grade;
    int column = movimentoTm.getColumnCount();
    //JtBanco.getColumnModel().getSelectedColumnCount();
    for (int i = 0; i < column; i++) {
      grade = this.jtMovimento.getColumnModel().getColumn(i).getPreferredWidth();
      System.out.println(jtMovimento.getColumnModel().getColumn(i).getHeaderValue()
              + " - " + grade);
    }
  }

  private void getPositionColumns() {
    System.out.println(jtMovimento.getColumnModel().getColumn(0).getHeaderValue());
  }

  public void selecionado() {
    habilitaJb(true, false, true, false, true);
    habilitaJtf(false);
    limpar();

    int linha = jtMovimento.getSelectedRow();//grava a linha selecionada
    int linhaSel = jtMovimento.convertRowIndexToModel(linha);

    if (linhaSel >= 0) { // executa o procedimento se o JTable não estiver vazio
      int colunaSel = jtMovimento.getSelectedColumn(); //grava a coluna selecionada
      boolean pesq = control.setEnabledPesquisa(colunaSel); // Verifica as colunas que serão habilitadas para pesquisa

      id = Integer.parseInt(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_ID).toString());
      jtfDataLancamento.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_DATA_LANCAMENTO).toString());
      jtfDataPrevisao.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_DATA_PREVISAO).toString());
      jtfObservacao.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_OBSERVACAO).toString());
      jtfIdCliente.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_ID_CLIENTE).toString());
      jtfNameCliente.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_CLIENTE).toString());
      jtfIdFornecedor.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_ID_FORNECEDOR).toString());
      jtfNameFornecedor.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_FORNECEDOR).toString());
      jtfIdTipo.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_ID_MOVIMENTO_TIPO).toString());
      jtfNameTipo.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_MOVIMENTO_TIPO).toString());
      jtfDataRealizado.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_DATA_REALIZADO).toString());
      jtfNumDocumento.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_NUM_DOCUMENTO).toString());
      jtfNumCheque.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_NUM_CHEQUE).toString());
      jtfValor.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_VALOR).toString());
      jcbStatus.getModel().setSelectedItem(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_STATUS).toString());

      control.modoConsulta = pesq;
      jbBuscar.setEnabled(pesq);
    }
  }

  public Movimento criaObjeto() {
    Movimento movimento = new Movimento();
    if (!jtfIdCliente.getText().isEmpty()) {
      movimento.setCliente(control.carregaCliente(Integer.parseInt(jtfIdCliente.getText())));
    }
    if (!jtfDataPrevisao.getText().isEmpty()) {
      movimento.setDataPrevisao(Util.formatDataSToD(jtfDataPrevisao.getText()));
    }
    if (!jtfDataRealizado.getText().isEmpty()) {
      movimento.setDataRealizado(Util.formatDataSToD(jtfDataRealizado.getText()));
    }
    if (!jtfIdFornecedor.getText().isEmpty()) {
      movimento.setFornecedor(control.carregaFornecedor(Integer.parseInt(jtfIdFornecedor.getText())));
    }
    if (!jtfNumDocumento.getText().isEmpty()) {
      movimento.setNumDocumento(Integer.parseInt(jtfNumDocumento.getText()));
    }
    if (!jtfNumCheque.getText().isEmpty()) {
      movimento.setNumeroCheque(Integer.parseInt(jtfNumCheque.getText()));
    }
    movimento.setContaBanco(contaBanco);
    movimento.setDataLancamento(Util.formatDataSToD(jtfDataLancamento.getText()));
    movimento.setMovimentoTipo(movimentoTipo);
    movimento.setObservacao(jtfObservacao.getText());
    movimento.setStatus(Status.valueOf(jcbStatus.getModel().getSelectedItem().toString()));
    movimento.setValor(new BigDecimal(jtfValor.getText()));

    if (id != null) {
      movimento.setId(id);
    }
    return movimento;
  }

  private void salvar() {
    control.salvar(criaObjeto());
    listar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (JOptionPane.showConfirmDialog(this, "Deseja inserir um novo registro", "", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
      novo();
    } else {
      setCellSelect(jtMovimento, movimentoTm, movimentoTm.getRowCount());
    }
  }

  private void listar() {
    setJtBancoTm(control.listar(contaBanco));
    limpar();
    setFirstCellSelect(jtMovimento, movimentoTm);
    StatusType.listarStatus(jcbStatus);
    getLarguraJtBanco();
  }

  private void limpar() {
    jtfDataPrevisao.setText(null);
    jtfDataRealizado.setText(null);
    jtfObservacao.setText(null);
    jtfDataLancamento.setText(null);
    id = null;
    jtfIdCliente.setText(null);
    jtfIdFornecedor.setText(null);
    jtfNameCliente.setText(null);
    jtfNameFornecedor.setText(null);
    jtfIdTipo.setText(null);
    jtfNameTipo.setText(null);
    jtfNumDocumento.setText(null);
    jtfNumCheque.setText(null);
    jtfValor.setText(null);
    jbBuscar.setEnabled(false);
  }

  public void setJtBancoTm(List<Movimento> ct) {
    removeAllJtable();
    if (!ct.isEmpty()) {
      movimentoTm.adicionaLista(ct);
    }
  }

  public void setJtCotacaoTm(Movimento ct) {
    removeAllJtable();
    if (ct != null) {
      movimentoTm.adiciona(ct);
    }
  }

  private void removeAllJtable() {
    while (movimentoTm.getRowCount() > 0) {
      movimentoTm.remove(0);
    }
  }

  /**
   * Determina quais os botões da barra de ferramentas ficará ativo
   *
   * @param novo
   * @param salvar
   * @param editar
   * @param cancelar
   * @param excluir
   */
  public void habilitaJb(Boolean novo, Boolean salvar, Boolean editar, Boolean cancelar,
          Boolean excluir) {
    JbNovo.setEnabled(novo);
    JbSalvar.setEnabled(salvar);
    JbEditar.setEnabled(editar);
    JbCancelar.setEnabled(cancelar);
    JbExcluir.setEnabled(excluir);
  }

  /**
   * Define se os JTextFields serão liberados para edição do usuário
   *
   * @param tf <b>True</b> - Habilitar; <b>False</b> - Desabilitar;
   */
  public void habilitaJtf(Boolean tf) {
    jtfDataPrevisao.setEnabled(tf);
    jtfObservacao.setEnabled(tf);
    jtfDataLancamento.setEnabled(tf);
    jtfIdCliente.setEnabled(tf);
    jtfIdFornecedor.setEnabled(tf);
    jtfNameCliente.setEnabled(tf);
    jtfNameFornecedor.setEnabled(tf);
    jtfDataRealizado.setEnabled(tf);
    jtfIdTipo.setEnabled(tf);
    jtfNameTipo.setEnabled(tf);
    jtfNumDocumento.setEnabled(tf);
    jtfNumCheque.setEnabled(tf);
    jtfValor.setEnabled(tf);
  }

  private void editar() {
    habilitaJb(false, true, false, true, false);
    habilitaJtf(true);
    jtfIdCliente.requestFocus();
  }

  private void excluir() {
    control.excluir(criaObjeto());
    listar();
    limpar();
  }

  private void cancelar() {
    limpar();
    habilitaJb(true, false, false, false, false);
    habilitaJtf(false);
    if (control.modoConsulta) {
      control.modoConsulta = false;
    } else {
      listar();
    }
  }

  private void selecionaRegistro() {
    int linha = jtMovimento.getSelectedRow();
    int linhaSel = jtMovimento.convertRowIndexToModel(linha);
    idPesquisa.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_DATA_PREVISAO).toString());
    razaoPesquisa.setText(movimentoTm.getValueAt(linhaSel, MovimentoTableModel.COLUNA_COD_ID_CLIENTE).toString());
    modoConsultaExt = false;
    this.dispose();
  }

  private void pesquisar() {
    setJtBancoTm(control.pesquisar());
    jlFiltro.setVisible(true);
    jbBuscar.setEnabled(false);
    limpar();
  }

  private void setFirstCellSelect(JTable table, AbstractTableModel model) {
    if (model.getRowCount() > 0) {
      table.setRowSelectionInterval(0, 0);
      table.setColumnSelectionInterval(0, 0);
      selecionado();
    }
  }

  private void setCellSelect(JTable table, AbstractTableModel model, int linha) {
    if (model.getRowCount() > 0) {
      table.setRowSelectionInterval(linha - 1, linha - 1);
      table.setColumnSelectionInterval(0, 0);
      selecionado();
    } else {
      Util.msgAdv("O número da linha informada é inválido");
    }
  }

  private String getDescConta(ContaBanco conta) {
    String descConta = contaBanco.getBanco().getCod()
            + " - " + contaBanco.getAgencia()
            + " - " + contaBanco.getConta()
            + " - " + contaBanco.getEmpresa().getFantasia();
    return descConta;
  }

  private void selecionaConta() {
    contaBanco = ContaBancoJDialog.getContaBancoPesquisa();
    if (contaBanco != null) {
      jtfIdConta.setText(String.valueOf(contaBanco.getId()));
      jtfDescConta.setText(getDescConta(contaBanco));
    }
  }

  private void selecionaTipo() {
    movimentoTipo = MovimentoTipoJDialog.getMovimentoTipoPesquisa();
    if (movimentoTipo != null) {
      jtfIdTipo.setText(String.valueOf(movimentoTipo.getId()));
      jtfNameTipo.setText(movimentoTipo.getDescricao());
    }
  }

  private void selecionaCliente() {
    ClienteJDialog.getInstance(null, true, jtfIdCliente, jtfNameCliente).setVisible(true);
  }

  private void selecionaFornecedor() {
    FornecedorJDialog.getInstance(null, true, jtfIdFornecedor, jtfNameFornecedor).setVisible(true);
  }

  private void validaTipo() {
    if (movimentoTipo != null) {
      jtfNumCheque.setEnabled(movimentoTipo.getIsCheque());
      jtfDataPrevisao.setEnabled(movimentoTipo.getRequestPrevision());
      jtfDataRealizado.setEnabled(!movimentoTipo.getRequestPrevision());
      jtfNumDocumento.setEnabled(movimentoTipo.getRequestNumber());
      if (movimentoTipo.getRequestEntity()) {
        if (movimentoTipo.getTipo() == Tipo.ENTRADA) {
          jtfIdCliente.setEnabled(true);
          jtfIdFornecedor.setEnabled(false);
        } else if (movimentoTipo.getTipo() == Tipo.SAIDA) {
          jtfIdCliente.setEnabled(false);
          jtfIdFornecedor.setEnabled(true);
        }
      } else {
        jtfIdCliente.setEnabled(movimentoTipo.getRequestEntity());
        jtfIdFornecedor.setEnabled(movimentoTipo.getRequestEntity());
      }
    }
  }

  public void reiniciar() {
    limpar();
    JbNovo.setEnabled(false);
    JbRefresh.setEnabled(false);
    jtfIdConta.setEnabled(true);
    jtfIdConta.requestFocus();
  }

  public Boolean isNotNull() {
    /*if (dialog.getJtfCnpj().getText().isEmpty()) {
     Util.msgAdv("Campo \"CNPJ\" vazio.");
     dialog.getJtfCnpj().requestFocus();
     return false;
     } else if (dialog.getJtfIe().getText().isEmpty()) {
     Util.msgAdv("Campo \"IE\" vazio.");
     dialog.getJtfIe().requestFocus();
     return false;
     } else if (dialog.getJtfRazao().getText().isEmpty()) {
     Util.msgAdv("Campo \"Razão\" vazio.");
     dialog.getJtfRazao().requestFocus();
     return false;
     } else if (dialog.getJtfIdCidade().getText().isEmpty()) {
     Util.msgAdv("Campo \"Id Cidade\" vazio.");
     dialog.getJtfIdCidade().requestFocus();
     return false;
     } else if (dialog.getJtfCep().getText().isEmpty()) {
     Util.msgAdv("Campo \"CEP\" vazio.");
     dialog.getJtfCep().requestFocus();
     return false;
     } else if (dialog.getJtfRua().getText().isEmpty()) {
     Util.msgAdv("Campo \"Endereço\" vazio.");
     dialog.getJtfRua().requestFocus();
     return false;
     } else if (dialog.getJtfBairro().getText().isEmpty()) {
     Util.msgAdv("Campo \"Bairro\" vazio.");
     dialog.getJtfBairro().requestFocus();
     return false;
     } else if (dialog.getJtfNumero().getText().isEmpty()) {
     Util.msgAdv("Campo \"Nº\" vazio.");
     dialog.getJtfNumero().requestFocus();
     return false;
     } else if (dialog.getJtfFantasia().getText().isEmpty()) {
     Util.msgAdv("Campo \"Nome Fantasia\" vazio.");
     dialog.getJtfFantasia().requestFocus();
     return false;
     }*/
    return true;
  }

  class ThreadReport extends Thread {

    @Override
    public void run() {
      try {
        control.report();
      } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, ex.getMessage());
      }
    }
  }
}
